<?php
/**
 * Front controller of qFw.
 */
class qFront
{
    /** Base directory of application. */
    private static $basedir;
    /** Use pretty URL? */
    private static $modrewrite = true;
    
    /**
     * Disables pretty URLs.
     */
    public static function DisableModRewrite()
    {
        self::$modrewrite = false;
    }
    
    /**
     * Sets base directory of application.
     * 
     * Base directory is used to determine which parts of URI are request elements, and which are path to application.
     * @param string $dir base directory of application.
     */
    public static function SetBaseDir($dir)
    {
    	if ($dir[0] != '/') $dir = '/' . $dir;
    	if ($dir[strlen($dir) - 1] == '/') $dir = substr($dir, 0, -1);
    	self::$basedir = $dir;
    }
    
    /**
     * Main function of qFront, runs application.
     * 
     * Finds request string and runs requested controllers.
     */
    public static function Run()
    {
        // load globals library, easy access to global tables
    	qLoader::LoadLibrary("globals");
    	qGlobals::Init();    
    	
        // get request without app path
	$request = qGlobals::Server("REQUEST_URI");
	$len = strlen(self::$basedir) + (self::$modrewrite ? 0 : 2);
	$request = substr($request, $len, strlen($request) - $len);
		
        // get controller's name and request string
	list($dummy, $controller, $request) = explode('/', $request, 3);
		
        // if they are empty, set them to index
	if ($controller == '')
            $controller = "index";
	if ($request == '')
            $request = "/index";
		
        // if error is to be shown, then show it
        if ($controller == "error")
        {
            qError::Run($request);
        }
        
        // if 'controller' is module name, then pass control to it
	if ($module = qLoader::GetModule($controller))
	{
	    $module->Module()->Run($request);
	}
        // if 'controller' is name of controller, then run it
	else if ($controller = qLoader::Controller($controller))
	{
	    $controller->Run($request);
            qTemplateParser::ParseController($controller);
	}
        // if nothing is found, then show HTTP: 404 error
	else
	{
            qError::Run("404");
	}
    }
}